from django.shortcuts import render
from .models import Book
from django.http import HttpResponse, HttpResponseRedirect
# 图书列表
def all_book(request):
    # 通过模型层查询出所有图书的数据
    # 显示活跃的数据
    # books = Book.objects.all()
    books = Book.objects.filter(is_active=True)
    # print(books)
    # 响应一个模板文件
    return render(request, 'bookstore/all_book.html', locals())
# 新增图书
def add_book(request):
    # 如果是GET请求，响应一个模板文件
    if request.method == 'GET':
        return render(request, 'bookstore/add_book.html')
    # 如果是POST请求，获取传递的参数，将其插入数据库中
    elif request.method == 'POST':
        # 获取请求的参数
        data = request.POST
        # <QueryDict: {'title': ['CSS'], 'pub': ['中信出版社'], 'price': ['81'], 'market_price': ['100']}>
        print(data)
        title = data['title']
        pub = data['pub']
        price = data['price']
        market_price = data['market_price']
        # 将数据插入到数据库
        try:
            Book.objects.create(title=title, pub=pub, price=price, market_price=market_price)
        except Exception as e:
            print('错误原因：', e)
            return HttpResponse('图书添加失败')
        else:
            # return HttpResponse('图书添加成功！')
            # 图书添加成功，跳转到列表页
            return HttpResponseRedirect('/bookstore/all_book')
# 修改图书
def update_book(request, book_id):
    # book_id 从路径中获取传递的id值
    # 查询出id对应的数据
    book = Book.objects.get(id=book_id)
    print(locals())
    # 如果是GET请求，将查询的这一本图书的数据渲染到表单控件，最后响应模板中
    if request.method == 'GET':
        return render(request, 'bookstore/update_book.html', locals())
    # 如果是POST请求，获取表单提交的数据，执行修改
    elif request.method == 'POST':
        # 获取POST传递的参数
        data = request.POST
        print(data)
        # 修改，给字段重新赋值
        book.price = data['price']
        book.market_price = data['market_price']
        # 保存
        book.save()
        # 成功后跳转到列表页
        return HttpResponseRedirect('/bookstore/all_book')
# 删除图书
def delete_book(request):
    # 获取GET传递的参数
    book_id = request.GET['book_id']
    print('book_id=', book_id)
    # 进行伪删除
    book = Book.objects.get(id=book_id)
    book.is_active = False
    book.save()
    # 跳转到列表页
    return HttpResponseRedirect('/bookstore/all_book')

